package com.warom.sdg.webview;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.warom.sdg.repository.PlcDataRepository;
import com.warom.sdg.repository.PlcDeviceRepository;
import com.warom.sdg.repository.PlcDeviceTypeRepository;
import com.warom.sdg.util.LogUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * WebView JavaScript接口基础抽象类
 * 提供共享功能和基础设施
 */
public abstract class BaseWebViewJsInterface {
    protected static final String TAG = "WebViewJsInterface";
    
    // 创建一个静态的Gson实例，以便在所有子类中复用
    protected static final Gson gson = new GsonBuilder().serializeNulls().create();
    
    protected Context context;
    protected PlcDeviceRepository deviceRepository;
    protected PlcDeviceTypeRepository deviceTypeRepository;
    protected PlcDataRepository dataRepository;
    protected WebViewWrapper webViewWrapper;
    protected Handler mainHandler;
    protected ExecutorService executor;
    
    /**
     * 构造函数
     * @param context 上下文
     * @param webViewWrapper WebView包装类，用于回调
     */
    public BaseWebViewJsInterface(Context context, WebViewWrapper webViewWrapper) {
        this.context = context;
        this.webViewWrapper = webViewWrapper;
        this.deviceRepository = new PlcDeviceRepository(context);
        this.deviceTypeRepository = new PlcDeviceTypeRepository(context);
        this.dataRepository = new PlcDataRepository(context);
        this.mainHandler = new Handler(Looper.getMainLooper());
        this.executor = Executors.newFixedThreadPool(2);
    }

    /**
     * 处理异步响应并调用JavaScript回调
     * @param requestId 请求ID
     * @param result 结果数据
     */
    protected void handleAsyncResponse(String requestId, String result) {
        mainHandler.post(() -> {
            if (webViewWrapper != null) {
                // 直接使用原始结果，不再包装ApiResponse
                String finalResult = result;
                // 调用JavaScript回调函数，传递请求ID和结果
                String jsCallback = "javascript:handleNativeResponse('" + requestId + "', " + finalResult + ")";
                webViewWrapper.evaluateJavascript(jsCallback);
                LogUtils.logOperation("WebView", "返回结果", "请求ID: " + requestId + ", 结果长度: " + finalResult.length() + " 字节");
            }
        });
    }
} 